home *** CD-ROM | disk | FTP | other *** search
/ Amiga Format CD 43 / Amiga Format CD43 (1999)(Future Publishing)(GB)(Track 1 of 2)[!][issue 1999-09].iso / -serious- / programming / other / python-1.52 / lib / python1.5 / amigapath.py < prev    next >
Text File  |  1999-06-14  |  10KB  |  357 lines

  1. # Module 'amigapath' -- common operations on Amiga pathnames.
  2. # Irmen de Jong, april 1st, 1996 (no joke)
  3. # (adapted from `posixpath.py')
  4. #
  5. # 26-mar-96: fixed split, islink. Improved expanduser.
  6. # 1-apr-96: fixed expanduser (works 100% now)
  7. # 25-dec-96: slight changes to comments and expanduser.
  8. # 27-jan-98: adapted to Python1.5
  9. # 26-apr-99: adapted to Python1.5.2
  10. #
  11. """Common pathname manipulations, Amiga version. 
  12. Instead of importing this module
  13. directly, import os and refer to this module as os.path.
  14. """
  15.  
  16. import os
  17. import stat
  18. import string
  19. import amiga
  20.  
  21. # Normalize the case of a pathname.
  22. normcase=string.lower
  23.  
  24.  
  25. # Return wheter a path is absolute.
  26.  
  27. def isabs(s):
  28.     """Test whether a path is absolute"""
  29.     return ':' in s
  30.  
  31.  
  32. # Join two pathnames.
  33. # Ignore the previous parts if a part is absolute.
  34. # Insert a '/' unless the first part is empty or already ends in '/' or ':'.
  35.  
  36. def join(a, *p):
  37.     """Join two or more pathname components, inserting '/' as needed"""
  38.     path = a
  39.     for b in p:
  40.         if ':' in b:
  41.             path = b
  42.         elif path == '' or path[-1:] == '/':
  43.             path = path + b
  44.         else:
  45.             if path[-1:]==':':
  46.                 path = path+b
  47.             else:
  48.                 path = path + '/' + b
  49.     return path
  50.  
  51.  
  52. # Split a path in head (everything up to the last '/') and tail (the
  53. # rest).  If the path ends in '/' or ':', tail will be empty.  If there is no
  54. # '/' or ':' in the path, head  will be empty.
  55. # Trailing '/'es are stripped from head unless it is the root.
  56. # DIFFERENCE WITH posixpath: only ONE trailing '/' will be stripped from head!
  57. # (on the Amiga a double slash means "parent dir"! ) This means that if
  58. # head ends in a '/', you MUST add a '/' to it when reconstructing the path,
  59. # or you will lose the "parent dir" slash.
  60. # Functions that depend on this function are also affected!
  61. #  (basename, dirname)
  62. #
  63. # Suggested by Kent Polk, kent@eaenki.nde.swri.edu
  64.  
  65. def split(p):
  66.     """Split a pathname.  Returns tuple "(head, tail)" where "tail" is 
  67. everything after the final slash.  Either part may be empty"""
  68.     i = string.rfind(p, '/')
  69.     j = string.rfind(p, ':')
  70.     if (i>j) and p[-1]=='/':
  71.         p=p[:-1]
  72.         i = string.rfind(p, '/')
  73.     if (j>i) or ((j>=0) and (i<0)): i=j
  74.     head, tail = p[:i+1], p[i+1:]
  75.     if head:
  76.         if head[-1]=='/': head=head[:-1]
  77.     return head, tail
  78.  
  79.  
  80. # Split a path in root and extension.
  81. # The extension is everything starting at the last dot in the last
  82. # pathname component; the root is everything before that.
  83. # It is always true that root + ext == p.
  84.  
  85. def splitext(p):
  86.     """Split the extension from a pathname.  Extension is everything from the
  87. last dot to the end.  Returns "(root, ext)", either part may be empty"""
  88.     root, ext = '', ''
  89.     for c in p:
  90.         if c == '/':
  91.             root, ext = root + ext + c, ''
  92.         elif c == '.':
  93.             if ext:
  94.                 root, ext = root + ext, c
  95.             else:
  96.                 ext = c
  97.         elif ext:
  98.             ext = ext + c
  99.         else:
  100.             root = root + c
  101.     return root, ext
  102.  
  103.  
  104. # Split a pathname into a drive specification and the rest of the
  105. # path.
  106.  
  107. def splitdrive(p):
  108.     """Split a pathname into drive and path. On Posix, drive is always 
  109. empty"""
  110.     i = string.rfind(p,':') + 1
  111.     if i<=0: return '', p
  112.     return p[:i],p[i:]
  113.  
  114.  
  115. # Return the tail (basename) part of a path.
  116.  
  117. def basename(p):
  118.     """Returns the final component of a pathname"""
  119.     return split(p)[1]
  120.  
  121.  
  122. # Return the head (dirname) part of a path.
  123.  
  124. def dirname(p):
  125.     """Returns the directory component of a pathname"""
  126.     return split(p)[0]
  127.  
  128.  
  129. # Return the longest prefix of all list elements.
  130.  
  131. def commonprefix(m):
  132.     "Given a list of pathnames, returns the longest common leading component"
  133.     if not m: return ''
  134.     prefix = m[0]
  135.     for item in m:
  136.         for i in range(len(prefix)):
  137.             if prefix[:i+1] <> item[:i+1]:
  138.                 prefix = prefix[:i]
  139.                 if i == 0: return ''
  140.                 break
  141.     return prefix
  142.  
  143. # Get size, mtime, atime of files.
  144.  
  145. def getsize(filename):
  146.     """Return the size of a file, reported by os.stat()."""
  147.     st = os.stat(filename)
  148.     return st[stat.ST_SIZE]
  149.  
  150. def getmtime(filename):
  151.     """Return the last modification time of a file, reported by os.stat()."""
  152.     st = os.stat(filename)
  153.     return st[stat.ST_MTIME]
  154.  
  155. def getatime(filename):
  156.     """Return the last access time of a file, reported by os.stat()."""
  157.     st = os.stat(filename)
  158.     return st[stat.ST_MTIME]
  159.  
  160. # Get the full pathname of a file/directory (i.e. expand assigns).
  161. fullpath = amiga.fullpath
  162.  
  163. # Is a path a symbolic link?
  164. # This will always return false on systems where os.lstat doesn't exist.
  165. # (or where S_ISLNK isn't defined)
  166.  
  167. def islink(path):
  168.     """Test whether a path is a symbolic link"""
  169.     try:
  170.         st = os.lstat(path)
  171.         return stat.S_ISLNK(st[stat.ST_MODE])
  172.     except (os.error, AttributeError):
  173.         return 0
  174.  
  175.  
  176. # Does a path exist?
  177. # This is false for dangling symbolic links.
  178.  
  179. def exists(path):
  180.     """Test whether a path exists.  Returns false for broken symbolic links"""
  181.     try:
  182.         st = os.stat(path)
  183.     except os.error:
  184.         return 0
  185.     return 1
  186.  
  187.  
  188. # Is a path a directory?
  189. # This follows symbolic links, so both islink() and isdir() can be true
  190. # for the same path.
  191.  
  192. def isdir(path):
  193.     """Test whether a path is a directory"""
  194.     try:
  195.         st = os.stat(path)
  196.     except os.error:
  197.         return 0
  198.     return stat.S_ISDIR(st[stat.ST_MODE])
  199.  
  200.  
  201. # Is a path a regular file?
  202. # This follows symbolic links, so both islink() and isfile() can be true
  203. # for the same path.
  204.  
  205. def isfile(path):
  206.     """Test whether a path is a regular file"""
  207.     try:
  208.         st = os.stat(path)
  209.     except os.error:
  210.         return 0
  211.     return stat.S_ISREG(st[stat.ST_MODE])
  212.  
  213.  
  214. # Are two filenames really pointing to the same file?
  215.  
  216. def samefile(f1, f2):
  217.     """Test whether two pathnames reference the same actual file"""
  218.     s1 = os.stat(f1)
  219.     s2 = os.stat(f2)
  220.     return samestat(s1, s2)
  221.  
  222.  
  223. # Are two open files really referencing the same file?
  224. # (Not necessarily the same file descriptor!)
  225.  
  226. def sameopenfile(fp1, fp2):
  227.     """Test whether two open file objects reference the same file"""
  228.     s1 = os.fstat(fp1)
  229.     s2 = os.fstat(fp2)
  230.     return samestat(s1, s2)
  231.  
  232.  
  233. # Are two stat buffers (obtained from stat, fstat or lstat)
  234. # describing the same file?
  235.  
  236. def samestat(s1, s2):
  237.     """Test whether two stat buffers reference the same file"""
  238.     return s1[stat.ST_INO] == s2[stat.ST_INO] and \
  239.        s1[stat.ST_DEV] == s2[stat.ST_DEV]
  240.  
  241.  
  242. # Is a path a mount point? Amiga: Is it a device name?
  243.  
  244. def ismount(path):
  245.     """Test whether a path is a mount point (Amiga: a device name)"""
  246.     drive,rest = splitdrive(path)
  247.     if rest=='':
  248.         return 1
  249.     else:
  250.         return 0
  251.  
  252.  
  253. # Directory tree walk.
  254. # For each directory under top (including top itself, but excluding
  255. # '.' and '..'), func(arg, dirname, filenames) is called, where
  256. # dirname is the name of the directory and filenames is the list
  257. # of files (and subdirectories etc.) in the directory.
  258. # The func may modify the filenames list, to implement a filter,
  259. # or to impose a different order of visiting.
  260.  
  261. def walk(top, func, arg):
  262.     """walk(top,func,args) calls func(arg, d, files) for each directory "d" 
  263. in the tree  rooted at "top" (including "top" itself).  "files" is a list
  264. of all the files and subdirs in directory "d".
  265. """
  266.     try:
  267.         names = os.listdir(top)
  268.     except os.error:
  269.         return
  270.     func(arg, top, names)
  271.     for name in names:
  272.          name = join(top, name)
  273.          if isdir(name) and not islink(name):
  274.              walk(name, func, arg)
  275.  
  276.  
  277. # Expand paths beginning with '~' or '~user'.
  278. # '~' means $HOME; '~user' means that user's home directory.
  279. # If the path doesn't begin with '~', or if the user or $HOME is unknown,
  280. # the path is returned unchanged (leaving error reporting to whatever
  281. # function is called with the expanded path as argument).
  282. # See also module 'glob' for expansion of *, ? and [...] in pathnames.
  283. # (A function should also be defined to do full *sh-style environment
  284. # variable expansion.)
  285.  
  286. def expanduser(path):
  287.     """Expand ~ and ~user constructions.  If user or $HOME is unknown, 
  288. do nothing"""
  289.     if path[:1] <> '~':
  290.         return path
  291.     i, n = 1, len(path)
  292.     while i < n and path[i] <> '/':
  293.         i = i+1
  294.     if i == 1:
  295.         if not os.environ.has_key('HOME'):
  296.             return path
  297.         userhome = os.environ['HOME']
  298.     else:
  299.         try:
  300.             import pwd
  301.             pwent = pwd.getpwnam(path[1:i])
  302.         except (KeyError,ImportError,SystemError):
  303.             return path            # ~user only works if pwd module works
  304.         userhome = pwent[5]
  305.     if userhome[-1:] == '/': i = i+1
  306.     return userhome + path[i:]
  307.  
  308.  
  309. # Expand paths containing shell variable substitutions.
  310. # This expands the forms $variable and ${variable} only.
  311. # Non-existant variables are left unchanged.
  312.  
  313. _varprog = None
  314.  
  315. def expandvars(path):
  316.     """Expand shell variables of form $var and ${var}.  Unknown variables
  317. are left unchanged"""
  318.     global _varprog
  319.     if '$' not in path:
  320.         return path
  321.     if not _varprog:
  322.         import re
  323.         _varprog = re.compile(r'\$(\w+|\{[^}]*\})')
  324.     i = 0
  325.     while 1:
  326.         m = _varprog.search(path, i)
  327.         if not m:
  328.             break
  329.         i, j = m.span(0)
  330.         name = m.group(1)
  331.         if name[:1] == '{' and name[-1:] == '}':
  332.             name = name[1:-1]
  333.         if os.environ.has_key(name):
  334.             tail = path[j:]
  335.             path = path[:i] + os.environ[name]
  336.             i = len(path)
  337.             path = path + tail
  338.         else:
  339.             i = j
  340.     return path
  341.  
  342.  
  343. # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
  344. # It should be understood that this may change the meaning of the path
  345. # if it contains symbolic links!
  346. # Note: does nothing on Amiga because x/y//z is different than x/y/z.
  347.  
  348. def normpath(path):
  349.     """Normalize path, eliminating double slashes, etc. (Not on Amiga)"""
  350.     return path;
  351.  
  352. # Return an absolute path.
  353. def abspath(path):
  354.     if not isabs(path):
  355.         path = join(os.getcwd(), path)
  356.     return normpath(path)
  357.